package com.mmy.study.interceptor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.mmy.study.dao.User;
import com.mmy.study.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if(!(handler instanceof HandlerMethod) ){
            return true;
        }

        if(StrUtil.isBlank(token)) {
            // 说明需要返回到登录页面
            throw new RuntimeException("token is null");
        }
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException e) {
            throw new RuntimeException(e.getMessage());
        }

        User sysUser = userService.loadUserByUsername(userId);
        if(sysUser == null) {
            // 用户不存在
            throw new RuntimeException("用户不存在");
        }
        // 用户密码加签 验证token

        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(sysUser.getPassword())).build();
        try {
            jwtVerifier.verify(token); // 验证token
        }catch(JWTVerificationException e) {
            throw new RuntimeException("token 验证失败");
        }
        return true;
    }
}
